package cn.alex.sso.project.service.impl;

import cn.alex.sso.framework.enums.StatusEnum;
import cn.alex.sso.project.entity.SysClient;
import cn.alex.sso.project.entity.SysClientAllow;
import cn.alex.sso.project.mapper.SysClientAllowMapper;
import cn.alex.sso.project.service.SysClientAllowService;
import cn.alex.sso.project.service.SysClientService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Alex
 * @description 针对表【sys_client_allow(应用授权表)】的数据库操作Service实现
 * @createDate 2024-09-24 17:05:38
 */
@Service
@RequiredArgsConstructor
public class SysClientAllowServiceImpl extends ServiceImpl<SysClientAllowMapper, SysClientAllow> implements SysClientAllowService {
    private final SysClientService clientService;

    @Override
    public List<SysClientAllow> getListByClientId(List<Long> clientIdList) {
        return baseMapper.selectList(new LambdaQueryWrapper<SysClientAllow>()
                .in(SysClientAllow::getClientId, clientIdList)
        );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void change(Long clientId, List<SysClientAllow> clientAllowList) {
        baseMapper.delete(new LambdaQueryWrapper<SysClientAllow>()
                .eq(SysClientAllow::getClientId, clientId)
        );

        List<SysClientAllow> uniqueClientAllowList = new ArrayList<>(clientAllowList.stream()
                .filter(item -> StrUtil.isNotBlank(item.getUrl()))
                .collect(Collectors.toMap(SysClientAllow::getUrl, c -> c, (c1, c2) -> c1.getStatus() == 2 ? c1 : c2))
                .values()
        );
        uniqueClientAllowList.forEach(item -> item.setClientId(clientId));
        this.saveBatch(uniqueClientAllowList);
    }

    @Override
    public List<SysClientAllow> getAllowListByUserId(Long userId) {
        List<SysClient> clientList = clientService.getAllowListByUserId(userId);
        if (CollUtil.isEmpty(clientList)) {
            return Collections.emptyList();
        }

        List<Long> clientIdList = clientList.stream().map(SysClient::getId).collect(Collectors.toList());

        return baseMapper.selectList(new LambdaQueryWrapper<SysClientAllow>()
                .in(SysClientAllow::getClientId, clientIdList)
                .eq(SysClientAllow::getStatus, StatusEnum.YES.getStatus())
        );
    }

    @Override
    public void removeByClientId(Long clientId) {
        baseMapper.delete(new LambdaQueryWrapper<SysClientAllow>()
                .eq(SysClientAllow::getClientId, clientId)
        );
    }
}




